package com.example.studyPlatform.controller.api;

import com.example.studyPlatform.bean.Comment;
import com.example.studyPlatform.controller.api.protocol.API_STATE;
import com.example.studyPlatform.mapper.CommentMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.example.studyPlatform.config.RoutingConstant.API_PATH;
import static com.example.studyPlatform.controller.api.kit.JsonUtils.*;

// api 外围检验分流  service 组装   mapper  查询
@AllArgsConstructor
@Controller
public class CommentApi {
    CommentMapper commentMapper;

    @ResponseBody
    //http://127.0.0.1:8090/api/content/posts/3/comments/tree_view?pages=0&page=0&sort=&size=5&total=0
    @GetMapping(API_PATH + "/content/posts/{id}/comments/tree_view")
    ObjectNode getPostComments(@PathVariable("id") Integer id, Integer page, Integer size) {
        try {
            List<Comment> r = commentMapper.getCommentsByPostId(id, page * size, size);
            ObjectNode res = mapper.createObjectNode();
            Boolean hasNext = commentMapper.getCommentsByPostId(id, (page + 1) * size, size).size() != 0;
            res.put("status", 200);
            res.put("message", "OK");
            res.put("pages", 10);
            res.put("total", r.size());
            res.put("page", page);
            res.put("rpp", 10);
            res.put("hasNext", hasNext);
            res.put("isFirst", page == 0);
            res.put("isLast", !hasNext);
            res.put("isEmpty", false);
            res.put("hasContent", true);
            res.put("commentCount", r.size());
            Map<String, Object> data = new HashMap<>();
            data.put("content", r);
            res.putPOJO("data", data);
            return res;
        } catch (Exception e) {
            e.printStackTrace();
            return toJson(API_STATE.SERVER_ERR);
        }
    }

    @ResponseBody
    @PostMapping(API_PATH + "/content/posts/comments")
    @Transactional(rollbackFor = Exception.class)
    ObjectNode publishComment(@RequestBody(required = true) Map<String, Object> map) throws Exception {
        Comment comment = new Comment();
        //https://q1.qlogo.cn/g?b=qq&nk=3365310020&s=40
        comment.setAuthorUrl((String) map.get("authorUrl"));
        comment.setEmail((String) map.get("email"));
        comment.setContent((String) map.get("content"));
        comment.setPostId((Integer) map.get("postId"));
        commentMapper.publish(comment);
        return toJson(API_STATE.SUCCESS);
    }


    // TODO 获取某文章下的弹幕
    void getPostBulletChat() {

    }

}

